<template>
  <div>
    <template v-if="id">
      <el-table :data="position" v-loading="loading" size="mini"
                :header-cell-style="{fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border>
        <!-- 顺序列 -->
        <el-table-column align="center" label="顺序" width="200" prop="tenantSerialNumber">
          <template slot-scope="scope">
            <span>第{{scope.row.tenantSerialNumber}}承租人</span>
          </template>
        </el-table-column>

        <!-- 承租人列 -->
        <el-table-column align="center" label="承租人" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.tenantName ? `${scope.row.tenantName}_${scope.row.tenantIdCardFour}` : '-' }}
          </template>
        </el-table-column>

        <!-- 建立租赁时间列 -->
        <el-table-column align="center" label="建立租赁时间" width="200">
          <template slot-scope="scope">
            <el-date-picker
                style="width: 150px;"
                v-if="scope.row.edit"
                v-model="scope.row.leaseRelationshipTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
            <span v-else>{{ scope.row.leaseRelationshipTime || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 保证金相关列 -->
        <el-table-column align="center" label="保证金">
          <!-- 缴纳保证金 -->
          <el-table-column align="center" label="缴纳保证金" width="200">
            <template slot-scope="scope">
              <el-input
                  v-if="scope.row.edit"
                  v-model="scope.row.newDeposit"
                  placeholder="缴纳保证金"
                  style="width: 100px">
              </el-input>
              <span v-else>{{ scope.row.newDeposit || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 缴纳时间 -->
          <el-table-column align="center" label="缴纳时间" width="200">
            <template slot-scope="scope">
              <el-date-picker
                  style="width: 150px;"
                  v-if="scope.row.edit"
                  v-model="scope.row.newDepositPaymentTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
              <span v-else>{{ scope.row.newDepositPaymentTime || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 归还保证金 -->
          <el-table-column align="center" label="归还保证金" width="200">
            <template slot-scope="scope">
              <el-input
                  v-if="scope.row.edit"
                  v-model="scope.row.newDepositReturned"
                  placeholder="归还保证金"
                  style="width: 100px">
              </el-input>
              <span v-else>{{ scope.row.newDepositReturned || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 归还时间 -->
          <el-table-column align="center" label="归还时间" width="200">
            <template slot-scope="scope">
              <el-date-picker
                  style="width: 150px;"
                  v-if="scope.row.edit"
                  v-model="scope.row.newDepositReturnTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
              <span v-else>{{ scope.row.newDepositReturnTime || '-' }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.status !== 0">
              <template v-if="!scope.row.edit">
                <el-button
                    v-if="showAdd"
                    icon="el-icon-edit"
                    type="primary"
                    size="mini"
                    @click="handlerEdit(scope.row)"
                    :disabled="isDisabled">
                  编辑
                </el-button>
              </template>
              <template v-else>
                <el-button
                    icon="el-icon-check"
                    type="primary"
                    size="mini"
                    @click="handlerPositionSave(scope.row)">
                  保存
                </el-button>
                <el-button
                    icon="el-icon-close"
                    type="danger"
                    size="mini"
                    @click="cancelEdit(scope.row)"
                    style="margin-left: 10px">
                  取消
                </el-button>
              </template>
            </template>
            <template v-else>
              非正式数据（未上报或审核中）
            </template>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-result v-else icon="warning" title="提示" subTitle="请先保存承租人信息再操作租赁关系"></el-result>
  </div>
</template>

<script>
import { getTenantRelationshipById, saveTenantRelationship } from "@/api/lessee";

export default {
  name: 'leaseSituation',
  props: ['id', 'isDisabled', 'uniqueId'],
  data() {
    return {
      position: [],
      loading: false,
      showAdd: true,
      originalData: {} // 用于保存编辑前的原始数据
    }
  },
  mounted() {
    this.getPositionList();
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getPositionList();
        }
      }
    }
  },
  methods: {
    handlerEdit(row) {
      // 保存原始数据以便取消编辑时恢复
      this.originalData = {
        ...row,
        leaseRelationshipTime: row.leaseRelationshipTime,
        newDeposit: row.newDeposit,
        newDepositPaymentTime: row.newDepositPaymentTime,
        newDepositReturned: row.newDepositReturned,
        newDepositReturnTime: row.newDepositReturnTime
      };

      this.$set(row, 'edit', true);
      this.showAdd = false;
    },

    cancelEdit(row) {
      // 恢复原始数据
      Object.assign(row, this.originalData);
      this.$set(row, 'edit', false);
      this.showAdd = true;
    },

    getPositionList() {
      this.loading = true;
      getTenantRelationshipById(this.uniqueId).then(res => {
        this.position = res.map(item => ({
          ...item,
          edit: false // 初始化时设置edit为false
        }));
      }).finally(() => {
        this.loading = false;
      });
    },

    handlerPositionSave(row) {
      this.loading = true;

      // 准备要保存的数据
      const saveData = {
        id: row.id,
        leaseRelationshipTime: row.leaseRelationshipTime,
        newDeposit: row.newDeposit,
        newDepositPaymentTime: row.newDepositPaymentTime,
        newDepositReturned: row.newDepositReturned,
        newDepositReturnTime: row.newDepositReturnTime,
        uniqueId: this.uniqueId
      };

      saveTenantRelationship(saveData).then(() => {
        this.$message.success('保存成功！');
        this.$set(row, 'edit', false);
        this.showAdd = true;
        this.getPositionList();
      }).finally(() => {
        this.loading = false;
      });
    }
  }
}
</script>
